c# asp.net Signalr 聊天室,服务端与客户端实现聊天室,广播,进度条,消息推送namespace UsersOnlineExample.Utils
{
using System.Collections.Generic;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
[HubName("userActivityHub")]
public class UserActivityHub : Hub
{
/// <summary>
/// 连接的用户数
/// </summary>
public static List<string> Users = new List<string>();
public void SendSingle()
{
// Call the addNewMessageToPage method to update clients.
var context = GlobalHost.ConnectionManager.GetHubContext<UserActivityHub>();
}
/// <summary>
/// Sends the update user count to the listening view.
/// </summary>
/// <param name="count">
/// The count.
/// </param>
public void Send(int count)
{
// Call the addNewMessageToPage method to update clients.
var context = GlobalHost.ConnectionManager.GetHubContext<UserActivityHub>();
context.Clients.All.updateUsersOnlineCount(count);
}
/// <summary>
/// The OnConnected event.
/// </summary>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
public override System.Threading.Tasks.Task OnConnected()
{
string clientId = GetClientId();
if (Users.IndexOf(clientId) == -1)
{
Users.Add(clientId);
}
// Send the current count of users
Send(Users.Count);
var context = GlobalHost.ConnectionManager.GetHubContext<UserActivityHub>();
context.Clients.Client(clientId).updateUserName(clientId);
return base.OnConnected();
}
/// <summary>
/// The OnReconnected event.
/// </summary>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
public override System.Threading.Tasks.Task OnReconnected()
{
string clientId = GetClientId();
if (Users.IndexOf(clientId) == -1)
{
Users.Add(clientId);
}
// Send the current count of users
Send(Users.Count);
return base.OnReconnected();
}
/// <summary>
/// The OnDisconnected event.
/// </summary>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
public override System.Threading.Tasks.Task OnDisconnected()
{
string clientId = GetClientId();
if (Users.IndexOf(clientId) > -1)
{
Users.Remove(clientId);
}
// Send the current count of users
Send(Users.Count);
return base.OnDisconnected();
}
/// <summary>
/// Get's the currently connected Id of the client.
/// This is unique for each client and is used to identify
/// a connection.
/// </summary>
/// <returns>The client Id.</returns>
private string GetClientId()
{
string clientId = "";
if (Context.QueryString["clientId"] != null)
{
// clientId passed from application
clientId = this.Context.QueryString["clientId"];
}
if (string.IsNullOrEmpty(clientId.Trim()))
{
clientId = Context.ConnectionId;
}
return clientId;
}
}
}
评论